package com.example.generator;

import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.java.TopLevelClass;

import java.util.List;

public class CustomPlugin extends PluginAdapter {
    @Override
    public boolean validate(List<String> warnings) {
        return true;
    }

    @Override
    public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        generateConstructor(topLevelClass, introspectedTable);
        return true;
    }

    private void generateConstructor(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        Method constructor = new Method(topLevelClass.getType().getShortName());
        constructor.setConstructor(true);
        constructor.setVisibility(org.mybatis.generator.api.dom.java.JavaVisibility.PUBLIC);

        introspectedTable.getAllColumns().forEach(column -> {
            FullyQualifiedJavaType type = column.getFullyQualifiedJavaType();
            String name = column.getJavaProperty();
            constructor.addParameter(new Parameter(type, name));
            constructor.addBodyLine("this." + name + " = " + name + ";");
        });

        topLevelClass.addMethod(constructor);
    }
}